//
//  UserLoginController.swift
//  wechatManager
//
//  Created by tangchunhui on 15/4/18.
//  Copyright (c) 2015年 tangchunhui. All rights reserved.
//

import Foundation


class UserLoginController:UIViewController{
    @IBOutlet var username:UITextField!
    @IBOutlet var password:UITextField!
    
    
    var md5str:String=""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        var userArray = DataModal.instance().queryData("User", whereString: "") as! Array<User>
        if (userArray.count>0){
            var user = userArray[0]
            self.md5str = user.md5str
            self.performSegueWithIdentifier("LoginSuccess", sender: nil)

            
        }

        
        
    }
    @IBAction func login(sender:AnyObject){
        self.username.resignFirstResponder()
        self.password.resignFirstResponder()
        var m = ModalLogin(username: username.text, password:  password.text)
        DataModal.instance().executeModal(m, withhud: true, completion: {(data:Dictionary!)->()  in
            var data1:Dictionary<String,String> = data as! Dictionary<String,String>
            var result = data1["result"]
            var md5str = data1["md5str"]
            if (result == "0"){
                DataModal.instance().deleteEntity("User", whereString: "")
                var user = DataModal.instance().createNewItem("User") as! User
                user.username = self.username.text
                user.md5str = md5str
                user.weixinhao = data1["weixinhao"]
                user.serverip = data1["serverip"]
                user.accesstoken = data1["access"]
                self.md5str = md5str!
                DataModal.instance().managedObjectContext.save(nil)
                
                dispatch_sync(dispatch_get_main_queue(),{
                self.performSegueWithIdentifier("LoginSuccess", sender: nil)
                })
            } else {
                dispatch_async(dispatch_get_main_queue(),{
                  Global.instance().showMessageDelay("登录失败，用户名或密码错")
                })
            }
        },failure:nil)
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        var vc = segue.destinationViewController as! ViewController
        vc.md5str = self.md5str
    }
    
}